package escenario;

public class CollisionDetector implements Runnable {

	private Escenario es;
	
	public CollisionDetector (Escenario es){
		setEscenario(es);
	}
	
	private static double truncate(double x){
	    long y=(long)(x*100);
	    return (double)y/100;
	}
	
	public Escenario getEscenario() {
		return es;
	}

	public void setEscenario(Escenario es) {
		this.es = es;
	}
	
	public boolean calculoColision(IdPosicion a, IdPosicion b){
		double temp1 = StrictMath.abs((a.getX()-b.getX()));
		double temp2 = StrictMath.abs((a.getY()-b.getY()));
		double temp3 = StrictMath.abs((a.getZ()-b.getZ()));
		
		if(temp1 < 2 && temp2 < 2 && temp3 < 2)
			return true;
		else
			return false;	
	}
	
	public void calculoColisionTotal(){
		for(int i=0; i < this.getEscenario().getSizePosEnemigos(); i++){
			for(int j=0; j < this.getEscenario().getSizePosEnemigos(); j++){
				
				if( (i!=j) && (this.getEscenario().getPosEnemigo(i) != null)
						&& (this.getEscenario().getPosEnemigo(j) != null) ){
							IdPosicion temp1 = this.getEscenario().getPosEnemigo(i);
							IdPosicion temp2 = this.getEscenario().getPosEnemigo(j);
			
							if(calculoColision(temp1, temp2)){
								this.getEscenario().getMisilesEnemigos(i).colision(this.getEscenario().getMisilesEnemigos(j));
					}
				}
			}
		}
	}
	
	public void printIdPos(){
		for(int i=0; i<this.getEscenario().getSizePosEnemigos(); i++){
			if(this.getEscenario().getPosEnemigo(i) != null){
				System.out.print(("ID:" + (int)(this.getEscenario().getPosEnemigo(i).getId()) + " X:"
						+ (int)(this.getEscenario().getPosEnemigo(i).getX()) + " Y:" 
						+ (int)(this.getEscenario().getPosEnemigo(i).getY()) + " Z:"
						+ (int)(this.getEscenario().getPosEnemigo(i).getZ()) + "        "));
			}
		}
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true){
			calculoColisionTotal();
			printIdPos();
			System.out.println();
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
}
